<?php
namespace app\bsadmin\controller;
use think\facade\Session;
use think\facade\Cache;
use think\facade\View;
use think\facade\Validate;
use think\helper\Str;
use think\facade\Db;
use app\bsadmin\model\Auth as AuthModel;
use app\bsadmin\model\Role as RoleModel;
use app\bsadmin\model\Admin as AdminModel;
use app\bsadmin\model\AdminLoginLog as AdminLoginLogModel;
use app\bsadmin\model\AdminLog as AdminLogModel;
use app\common\model\WechatQrcode as WechatQrcodeModel;
use app\common\model\AdminNotice as AdminNoticeModel;
use helper\URL;
use helper\Wechat;
use app\common\QrcodeUtil;
class Admin extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['rid']) {
                $where[]=['admin.role_id','=',$G['rid']];
            }
            if ($G['nickname']) {
                $where[]=['admin.nickname','like','%'.$G['nickname'].'%'];
            }
            if ($G['username']) {
                $where[]=['admin.username','like','%'.$G['username'].'%'];
            }
            if ($G['status']!='all') {
                $where[]=['admin.status','=',$G['status']];
            }
            $Data=AdminModel::alias('admin')->where($where)
                ->join('role role','role.rid = admin.role_id')
                ->field('admin.*,role.title')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['allow_week']=explode(",", $v['allow_week']);
                    $v['login_time']=$v['login_time']?date('Y-m-d H:i:s',$v['login_time']):'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            View::assign('role',RoleModel::getCateList());
            return View::fetch();
        }
    }
    public function addAdmin()
    {
        if (request()->isAjax()) {
            $D=request()->post();
            $rule =   [
                'role_id'           => 'require',
                'nickname'          => 'require|max:30',
                'username'          => 'require|length:6,25|unique:admin',
                'password'          => 'require|length:6,25',
                'allow_time_start'  => 'require',
                'allow_time_end'    => 'require|gt:allow_time_start',
                'allow_week'        => 'require|array',
            ];
            $msg  =   [
                'role_id.require'           => '请选择角色', 
                'nickname.require'          => '请输入昵称', 
                'nickname.max'              => '昵称不能超过30个字符', 
                'username.require'          => '用户名不能为空',
                'username.unique'           => '该管理员已存在',
                'username.length'           => '用户名长度应在6~25位之间',
                'password.require'          => '密码不能为空',
                'password.length'           => '密码长度应在6~25位之间',
                'allow_time_start.require'  => '请输入允许开始时间',
                'allow_time_end.require'    => '请输入允许结束时间',
                'allow_time_end.gt'         => '结束时间需大于开始时间',
                'allow_week.require'        => '请选择工作日',
                'allow_week.array'          => '工作日不合法',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $passHash=Str::random(4);
            $adminModel=new AdminModel;
            $adminModel->headimg        = $D['headimg'];
            $adminModel->nickname       = $D['nickname'];
            $adminModel->username       = $D['username'];
            $adminModel->password       = AdminModel::getAdminPassword($passHash,$D['password']);
            $adminModel->password_hash  = $passHash;
            $adminModel->status         = $D['status'];
            $adminModel->mobile         = $D['mobile'];
            $adminModel->email          = $D['email'];
            $adminModel->other_contact  = $D['other_contact'];
            $adminModel->other_img      = $D['other_img'];
            $adminModel->adviser_default= $D['adviser_default'];
            $adminModel->role_id        = $D['role_id'];
            $adminModel->allow_time_start= $D['allow_time_start'];
            $adminModel->allow_time_end = $D['allow_time_end'];
            if($D['openid'])
            $adminModel->openid         = $D['openid'];
            if($D['pc_openid'])
            $adminModel->pc_openid         = $D['pc_openid'];
            $adminModel->allow_week     = implode(',', $D['allow_week']);
            if($adminModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            View::assign('role',RoleModel::getCateList());
            return View::fetch();
        }
    }
    public function editAdmin($id)
    {
        if (request()->isAjax()) {
            $D=request()->post();
            $rule =   [
                'role_id'           => 'require',
                'nickname'          => 'require|max:30',
                'username'          => 'require|unique:admin|length:6,25',
                'password'          => 'length:6,25',
                'allow_time_start'  => 'require',
                'allow_time_end'    => 'require|gt:allow_time_start',
                'allow_week'        => 'require|array',
            ];
            $msg  =   [
                'role_id.require'           => '请选择角色', 
                'nickname.require'          => '请输入昵称', 
                'nickname.max'              => '昵称不能超过30个字符', 
                'username.require'          => '用户名不能为空',
                'username.unique'           => '该管理员已存在',
                'username.length'           => '用户名长度应在6~25位之间',
                'password.length'           => '密码长度应在6~25位之间',
                'allow_time_start.require'  => '请输入允许开始时间',
                'allow_time_end.require'    => '请输入允许结束时间',
                'allow_time_end.gt'         => '结束时间需大于开始时间',
                'allow_week.require'        => '请选择工作日',
                'allow_week.array'          => '工作日不合法',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $passHash=Str::random(4);
            $adminModel=AdminModel::where(['id'=>$id])->find();
            $adminModel->nickname       = $D['nickname'];
            $adminModel->headimg        = $D['headimg'];
            $adminModel->username       = $D['username'];
            if (!empty($D['password'])) {
                $adminModel->password       = AdminModel::getAdminPassword($passHash,$D['password']);
                $adminModel->password_hash  = $passHash;
            }
            $adminModel->status         = $D['status'];
            $adminModel->mobile         = $D['mobile'];
            $adminModel->email          = $D['email'];
            $adminModel->other_contact  = $D['other_contact'];
            $adminModel->other_img      = $D['other_img'];
            $adminModel->adviser_default= $D['adviser_default'];
            $adminModel->role_id        = $D['role_id'];
            $adminModel->allow_time_start= $D['allow_time_start'];
            $adminModel->allow_time_end = $D['allow_time_end'];
            $adminModel->allow_week     = implode(',', $D['allow_week']);
            if($D['openid']){
                $adminModel->openid         = $D['openid'];
            }else{
                $adminModel->openid         = null;
            }
            if($D['pc_openid']){
                $adminModel->pc_openid         = $D['pc_openid'];
            }else{
                $adminModel->pc_openid         = null;
            }
            if($adminModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            View::assign('role',RoleModel::getCateList());
            $Find=AdminModel::editAdmin(['id'=>$id]);
            if ($Find) {
                View::assign('Find',$Find);
            }
            return View::fetch('add_admin');
        }
    }
    public function editMy()
    {
        if (request()->isAjax()) {
            $D=request()->post();
            $rule =   [
                'role_id'           => 'require',
                'nickname'          => 'require|max:30',
                'username'          => 'require|unique:admin|length:6,25',
                'password'          => 'length:6,25',
                'allow_time_start'  => 'require',
                'allow_time_end'    => 'require|gt:allow_time_start',
                'allow_week'        => 'require|array',
            ];
            $msg  =   [
                'role_id.require'           => '请选择角色', 
                'nickname.require'          => '请输入昵称', 
                'nickname.max'              => '昵称不能超过30个字符',
                'username.require'          => '用户名不能为空',
                'username.unique'           => '该管理员已存在',
                'username.length'           => '用户名长度应在6~25位之间', 
                'password.length'           => '密码长度应在6~25位之间',
                'allow_time_start.require'  => '请输入允许开始时间',
                'allow_time_end.require'    => '请输入允许结束时间',
                'allow_time_end.gt'         => '结束时间需大于开始时间',
                'allow_week.require'        => '请选择工作日',
                'allow_week.array'          => '工作日不合法',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $passHash=Str::random(4);
            $adminModel=AdminModel::where(['id'=>Session::get('AdminUser.uid')])->find();
            $adminModel->nickname       = $D['nickname'];
            $adminModel->headimg        = $D['headimg'];
            $adminModel->username       = $D['username'];
            if (!empty($D['password'])) {
                $adminModel->password       = AdminModel::getAdminPassword($passHash,$D['password']);
                $adminModel->password_hash  = $passHash;
            }
            $adminModel->mobile         = $D['mobile'];
            $adminModel->email          = $D['email'];
            $adminModel->other_contact  = $D['other_contact'];
            $adminModel->other_img      = $D['other_img'];
            if($D['openid']){
                $adminModel->openid         = $D['openid'];
            }else{
                $adminModel->openid         = null;
            }
            if($D['pc_openid']){
                $adminModel->pc_openid         = $D['pc_openid'];
            }else{
                $adminModel->pc_openid         = null;
            }
            if($adminModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            $Find=AdminModel::editAdmin(['id'=>Session::get('AdminUser.uid')]);
            if ($Find) {
                View::assign('Find',$Find);
            }
            return View::fetch('my_admin');
        }
    }
    public function bind()
    {
        $G=request()->get();
        $uid=request()->get('uid');
        if (empty($G['push'])) {
            $wxLoginConfig=config('wxlogin');
            if (empty($wxLoginConfig['status']) || !$wxLoginConfig['status'])
                return redirect('/unauthorized?msg=未开通微信登录');
            $type=request()->get('type');
            //-------生成唯一随机串防CSRF攻击
            $state = md5(uniqid(rand(), TRUE));
            Session::set('bindadmin_wechat',[
                'uid'=>$uid,
                'state'=>$state,
                'domain'=>request()->domain(),
                'type'=>$type
            ]);
            //-------构造请求参数列表
            $keysArr = [
                "response_type"     => "code",
                "scope"             => "snsapi_login",
                "appid"             => $wxLoginConfig['appid'],
                "redirect_uri"      => config('web.url').'/login/bindadmin',
                "state"             => $state
            ];
            return redirect(URL::combineURL("https://open.weixin.qq.com/connect/qrconnect", $keysArr).'#wechat_redirect');
        }else{
            $qrcodePath='/uploads/bindadmin/'.date('Ym');
            if (!file_exists('.'.$qrcodePath))
                mkdir('.'.$qrcodePath, 0777, true);
            $qrcodeFilename='admin_id_'.$uid;
            $qrcode=$qrcodePath.'/'.$qrcodeFilename.'.png';

            $WechatQrcodeModel=WechatQrcodeModel::where(['type'=>'bindadmin','qr_type'=>0,'alias_id'=>$uid])->whereTime('expire_time','>',time())->find();
            if(!$WechatQrcodeModel){
                $WechatQrcodeModel=new WechatQrcodeModel;
                $WechatQrcodeModel->type='bindadmin';
                $WechatQrcodeModel->qr_type=0;
                $WechatQrcodeModel->alias_id=$uid;
                $Data=[
                    'scene'=>[
                        'scene_str'=>'bindadmin_'.$uid
                    ]
                ];
                try {
                    $ret=Wechat::createQrScene($Data);
                } catch (Exception $e) {
                    return false;
                }
                if(empty($ret['url']))
                    return false;
                $WechatQrcodeModel->ticket=$ret['ticket'];
                $WechatQrcodeModel->expire_seconds=$ret['expire_seconds'];
                $WechatQrcodeModel->url=$ret['url'];
                $WechatQrcodeModel->expire_time=time()+$ret['expire_seconds'];
                $WechatQrcodeModel->save();
            }
            $url=$WechatQrcodeModel->url;
            $logo_url=str_replace('/public/','/',config('web.icon'));
            $logo_url=str_replace('/uploads','uploads',$logo_url);
            $qrObj=new QrcodeUtil([
                'size'      =>  200,
                'logo'      =>  true,
                'logo_size' =>  20,
                'logo_url'  =>  $logo_url,
                'file_path' =>  '.'.$qrcodePath,
                'file_name' =>  $qrcodeFilename,
            ]);
            return response($qrObj->createServer($url))->header([
                'Content-Type'=>$qrObj->_qr->getContentType()
            ]);
        }
    }
    /**
     * 设置管理员状态
     */
    public function setAdminStatus($id,$status)
    {
        $adminData=AdminModel::where('id',$id)->find();
        $adminData->status=$status;
        if ($adminData->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    /**
     * 获取管理员日志
     */
    public function getAdminLog()
    {
        $G=request()->get();
        if($G['type'] == 'login'){
            $adminLog=AdminLoginLogModel::where(['admin_id'=>$G['id']])->order('id desc')->paginate(10);
            if($adminLog->items()){
                return $this->ajaxReturn('success',0,$adminLog);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }elseif($G['type'] == 'log'){
            $adminLog=AdminLogModel::where(['l_uid'=>$G['id']])->order('lid desc')->paginate(10);
            if($adminLog->items()){
                return $this->ajaxReturn('success',0,$adminLog);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }
    }
    public function adminNotice()
    {
        $TypeList=['pay', 'resume_examine', 'jobs_examine', 'real_name', 'company_attestation', 'report_resume', 'report_jobs', 'feedback','enterprises'
        ,'user_pictured_audit','enterprise_logo','mp_send_notice'];
        if(request()->isPost()){
            $D=request()->post();
            $Data=[];
            foreach ($TypeList as $key => $value) {
                if(!empty($D[$value])){
                    foreach ($D[$value] as $k => $v) {
                        $temp['admin_id']=$v;
                        $temp[$value]=1;
                        ksort($temp);
                        $Data[$v]=$temp;
                    }
                }
            }
            sort($Data);
            // 启动事务
            Db::startTrans();
            try {
                Db::query('TRUNCATE TABLE '.config('database.connections.mysql.prefix').'admin_notice');
                if(!empty($Data)){
                    $AdminNoticeModel=new AdminNoticeModel;
                    $AdminNoticeModel->saveAll($Data);
                }
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100,['msg'=>$e->getMessage(),'line'=>$e->getLine()]);
            }
        }else{
            $Find=[];
            foreach ($TypeList as $k => $v) {
                $Find[$v]=AdminNoticeModel::where([$v=>1])->column('admin_id');
            }
            View::assign('Find',$Find);
            $AdminModel=AdminModel::alias('admin')->join('role role','role.rid=admin.role_id')->field('admin.id,admin.nickname,role.title')->select();
            View::assign('admin',$AdminModel);
            return View::fetch();
        }
    }
}









